package com.jci.vsd.activity;

import android.Manifest;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.jci.vsd.R;
import com.jci.vsd.activity.enterprise.RegisterCompanyActivity;

import com.jci.vsd.application.VsdApplication;
import com.jci.vsd.bean.UserBean;
import com.jci.vsd.bean.login.LoginResponseUserBean;
import com.jci.vsd.constant.MySpEdit;
import com.jci.vsd.data.UserData;
import com.jci.vsd.network.control.LoginApiControl;
import com.jci.vsd.observer.CommonDialogObserver;
import com.jci.vsd.observer.RxHelper;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.utils.Utils;
import com.jci.vsd.view.widget.SimpleToast;

import java.util.List;

import butterknife.BindView;

import cn.unitid.spark.cm.sdk.business.CBSCertificateStore;
import cn.unitid.spark.cm.sdk.business.service.CertificateService;
import cn.unitid.spark.cm.sdk.business.service.DeleteCertService;
import cn.unitid.spark.cm.sdk.data.entity.Certificate;
import cn.unitid.spark.cm.sdk.data.response.DataProcessResponse;
import cn.unitid.spark.cm.sdk.exception.CmSdkException;
import cn.unitid.spark.cm.sdk.listener.DataListener;
import cn.unitid.spark.cm.sdk.listener.ProcessListener;
import io.reactivex.Observable;

/**
 * Created by Victor on 10/31/2017.
 * 登录
 */

public class LoginActivity extends BaseActivity implements DataListener {


    private MySpEdit prefs;
    private Button btnSure;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.edt_acount)
    EditText edtAccount;
    @BindView(R.id.edt_psw)
    EditText edtPsw;

    private Dialog dialog;
    private View inflate;
    private TextView cancel;
    private TextView tvSelectCompany;
    private TextView tvRegisterCompany;
    private List<Certificate> certificateArrayList;//证书列表;
    private String exitCertName; //申请证书姓名
    private String userId;
    private String encCertId; //签名证书id
    private String signCerId;//证书id

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login_new);
        checkAuthority();
//        spRealName = MySpEdit.getInstance().getRealName();
        //  checkCBScert();
        btnSure = (Button) findViewById(R.id.btn_sure);
        prefs = MySpEdit.getInstance();
        String numPhone = prefs.getUser();
        String psw = prefs.getPsw();
        if (!TextUtils.isEmpty(numPhone)) {
            edtAccount.setText(numPhone);
        }
        if (!TextUtils.isEmpty(psw)) {
            edtPsw.setText(psw);
        }
        tvRegister.setText(Html.fromHtml(getResources().getString(R.string.str_register, 1, "", "去注册")));
        initViewEvent();
        userId = VsdApplication.getUserId();
    }

    @Override
    protected void initViewEvent() {
        tvRegister.setOnClickListener(this);
        btnSure.setOnClickListener(this);
    }

    //用户权限检测
    private void checkAuthority() {


        if (PermissionsUtil.hasPermission(LoginActivity.this, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {


        } else {
            PermissionsUtil.requestPermission(LoginActivity.this, new PermissionListener() {
                        @Override
                        public void permissionGranted(@NonNull String[] permission) {
                            Log.e("--", "permissionGranted: 用户授予了访问外部存储的权限");


                        }

                        @Override
                        public void permissionDenied(@NonNull String[] permission) {
                            Log.e("--", "permissionDenied: 用户拒绝了访问外部存储的申请");
                        }
                    }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        String numPhone = prefs.getUser();
        String psw = prefs.getPsw();
        if (!TextUtils.isEmpty(numPhone)) {
            edtAccount.setText(numPhone);
        }
        if (!TextUtils.isEmpty(psw)) {
            edtPsw.setText(psw);
        }
        CertificateService service = new CertificateService(userId, this);
        service.getCertificateList();
        // initTestData();
    }


    /**
     * 登陆网络请求
     * RxJava的进度框
     */

    private void login(final String userName, final String pwd, final String type) {

        Observable<LoginResponseUserBean> observable = new LoginApiControl().loginResponseWithHttps(userName, pwd);

        CommonDialogObserver<LoginResponseUserBean> observer = new CommonDialogObserver<LoginResponseUserBean>(this) {

            @Override
            public void onNext(LoginResponseUserBean responseBean) {
                super.onNext(responseBean);
                Loger.i("===login====" + new Gson().toJson(responseBean));
                String status = responseBean.getStatus();
                String companyId = responseBean.getCo();
                String dpt = responseBean.getDpt();
                String role = responseBean.getRole();
                String realName = responseBean.getRealname();
                String phone = responseBean.getPhone();
                String userId = responseBean.getId();
                if (companyId.equals("-1") && dpt.equals("-1") && role.equals("-1")) {
                    //被误删除后，需要重新加入公司
                    toActivityWithType(FillCodeActivity.class, "login");

                    return;
                }
                if (status.equals("200")) {
                    saveUserInfo(responseBean);
                    //判断是否有公司信息
                    boolean hasCompanyInfo = hasCompanyInfo(companyId, role);
                    if (hasCompanyInfo) {
                        prefs.setCompanyId(companyId);
                        prefs.setUserId(userId);
                        prefs.setRole(role);
                        prefs.setUser(phone);
                        prefs.setPsw(edtPsw.getText().toString().trim());
                        SimpleToast.toastMessage("登录成功", Toast.LENGTH_SHORT);
                        toActivity(MainNewActivity.class);

                    }
                }

                //判断证书的一致性

//                if (status.equals("200")) {
//                    saveUserInfo(responseBean);
//                    boolean hasCompanyInfo = hasCompanyInfo(companyId, role);
//                    exitCertName = MySpEdit.getInstance().getRealName();
//                    Loger.e("---login-certRealName--" + exitCertName);
//                    boolean isCertifateIllegal = checkCert(realName, exitCertName);
//
//                    //--start--form 校验证书 和登录人是否一致
//
////                    if (!isCertifateIllegal) {
////                        SimpleToast.toastMessage("证书和登录用户身份不符,请先去删除证书", Toast.LENGTH_SHORT);
////                    }
//
//
////                    if (hasCompanyInfo && isCertifateIllegal) {
////                        prefs.setCompanyId(companyId);
////                        prefs.setUserId(userId);
////                        prefs.setRole(role);
////                        prefs.setUser(phone);
////                        prefs.setPsw(edtPsw.getText().toString().trim());
////                        SimpleToast.toastMessage("登录成功", Toast.LENGTH_SHORT);
////                      //  toActivityWithType(MainActivity.class, role);
////
////                        toActivityWithType(MainNewActivity.class, role);
////
////                    }
//
//
//                }

                else if (status.equals("201")) {
                    SimpleToast.toastMessage("登录201", Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                SimpleToast.toastMessage(t.getMessage(), Toast.LENGTH_SHORT);
            }
        };

        RxHelper.bindOnUIActivityLifeCycle(observable, observer, LoginActivity.this);
    }

    //判断证书和登录用户身份是否符合
    private Boolean checkCert(String realName, String exitCertName) {


        if (exitCertName.equals(realName)) {
            return true;
        } else {
//            SimpleToast.toastMessage("证书和登录用户身份不符,请先去删除证书", Toast.LENGTH_SHORT);

            return false;
        }
    }

    //保存用户信息
    private void saveUserInfo(LoginResponseUserBean responseBean) {

        UserBean userBean = new UserBean();
//                    userBean.setPassword(responseBean.get);
        userBean.setPhone(responseBean.getPhone());
        userBean.setId(responseBean.getId());
        userBean.setType(responseBean.getRole());
        userBean.setDepart(responseBean.getDptname());
        userBean.setRealName(responseBean.getRealname());
        userBean.setHeadImg(responseBean.getHeadImg());

        Loger.e("--responseBean.getRole()" + responseBean.getRole());
        UserData.saveUser(userBean);
    }

    //是否有所属公司

    private boolean hasCompanyInfo(String companyId, String role) {
        if (companyId.equals("-1") && role.equals("1")) {
            //是boss，但还未创建公司
            SimpleToast.toastMessage("还未注册公司，请先去注册公司", Toast.LENGTH_SHORT);
            toActivityWithType(RegisterCompanyActivity.class, role);
            return false;

        } else if (companyId.equals("-1") && !role.equals("1")) {
            // 不是boss，且未加入公司
            SimpleToast.toastMessage("还未加入公司，请先加入公司", Toast.LENGTH_SHORT);
            toActivity(FillCodeActivity.class);
            return false;
        }
        return true;
    }


    /**
     * 删除证书
     */
    private void deleteCertificate() {
        //showLoading("正在删除，请稍候...");

        DeleteCertService deleteCertService = new DeleteCertService(this, userId, new
                ProcessListener<DataProcessResponse>() {
                    @Override
                    public void doFinish(DataProcessResponse a, String cert) {


                        SimpleToast.toastMessage("删除成功！", Toast.LENGTH_SHORT);
                        toActivity(RegisterCertActivity.class);

                        finish();
                    }

                    @Override
                    public void doCancel() {
                        // hideLoading();
                        Log.e("deleteCertificate", "doCancel");
                    }

                    @Override
                    public void doException(CmSdkException exception) {
                        //  hideLoading();
                        Log.e("deleteCertificate", "doException:" + exception.getMessage());
                        // Toast.makeText(CertificateDetailActivity.this, exception.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

//        signCertId = intent.getStringExtra("signCertId");
//        encCertificateId = intent.getStringExtra("encCertId");
        deleteCertService.deleteCertificate(signCerId, encCertId);
    }


    @Override
    public void onClick(View view) {
        //  super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_register:

                showDialog();

                break;
            case R.id.btn_sure:
                checkData();
                break;
            case R.id.tv_select_company:
                //加入公司
                toActivity(FillCodeActivity.class);
//                finish();
                dialog.dismiss();
                break;
            case R.id.tv_register_company:

                //创建公司 -先去填写个人信息
                toActivityWithType(RegisterActivity.class, "1");
//                finish();

                dialog.dismiss();
                break;
            case R.id.btn_cancel:
                dialog.dismiss();
                break;

            default:
                break;

        }


    }

    //判空
    private void checkData() {
        String accountStr = edtAccount.getText().toString().trim();
        String pswStr = edtPsw.getText().toString().trim();
        if (TextUtils.isEmpty(accountStr)) {
            SimpleToast.toastMessage("帐号不可为空！", Toast.LENGTH_SHORT);
            edtAccount.requestFocus();
            return;

        }

        if (TextUtils.isEmpty(pswStr)) {
            SimpleToast.toastMessage("密码不可为空！", Toast.LENGTH_SHORT);
            edtPsw.requestFocus();
            return;
        }
        //login_
        if (Utils.isNetworkAvailable(LoginActivity.this)) {
            login(accountStr, pswStr, "1");
        } else {
            SimpleToast.toastMessage("暂无网络，请先去设置网络", Toast.LENGTH_SHORT);
        }


    }


    public void showDialog() {
        dialog = new Dialog(this, R.style.BottomDialog);
        inflate = LayoutInflater.from(this).inflate(R.layout.dialog_choose_role, null);
        tvRegisterCompany = (TextView) inflate.findViewById(R.id.tv_register_company);
        tvSelectCompany = (TextView) inflate.findViewById(R.id.tv_select_company);
        cancel = (TextView) inflate.findViewById(R.id.btn_cancel);
        tvRegisterCompany.setOnClickListener(this);
        tvSelectCompany.setOnClickListener(this);
        cancel.setOnClickListener(this);
        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        // WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //获得window窗口的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        dialogWindow.setAttributes(lp);
        //将自定义布局加载到dialog上
        dialog.setContentView(inflate);
        dialog.show();
    }


    @Override
    protected void onDestroy() {
        if (dialog != null) {
            dialog.dismiss();
        }
        super.onDestroy();
        VsdApplication.getRefWatcher(this).watch(this);

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        System.exit(0);
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        // Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//
//        Intent intent = new Intent(LoginActivity.this, MainNewActivity.class);
//        startActivity(intent);
//        finish();
//    }

    @Override
    public void onData(List<Certificate> certificates) {
        Loger.e("--onData--ListCertifi");
        certificateArrayList = certificates;
        Certificate certificate = null;
        //证书检测，先跳过
//        if (certificateArrayList.size() == 0) {
//            //先去申请证书
//            SimpleToast.ToastMessage("请先申请个人证书！");
//            toActivity(RegisterCertActivity.class);
//            return;
//        } else {
//            certificate = certificateArrayList.get(0);
//            try {
//                String subjectDN = certificate.getX509Certificate().getSubjectDN();
//                Loger.e("---subjectDn--" + subjectDN);
//                String[] certInfoArray = subjectDN.split(",");
//                for (int i = 0; i < certInfoArray.length; i++) {
//                    Loger.e("---subjectArray--" + certInfoArray[i]);
//                }
//            } catch (CertificateEncodingException e) {
//                e.printStackTrace();
//            }
//            signCerId = certificate.getId();
//            certificateArrayList.get(0).getX509Certificate();
//
//            encCertId = certificateArrayList.get(0).getEncCertId();
//            exitCertName = certificateArrayList.get(0).getName();
//
//        }
    }


}
